import { PlusOutlined } from '@ant-design/icons'
import { Button, Divider, Input, Popconfirm, Table, message, DatePicker, Select } from 'antd'
import React, { useState, useEffect } from 'react'
import styles from '../style.less'
import { connect } from 'umi'
import { yesOrNoList, genderList,relationList } from '@/utils/constant'

const { Option } = Select
import {
  getFamilyInfo,
  addFamilyInfo,
  updateFamilyInfo,
  deleteFamilyInfo
} from '@/pages/Recruitment/Employee/service'
import { checkPhone } from '@/utils/utils';

const TableForm = ({ value, onChange, dispatch, employeeId }) => {
  const [clickedCancel, setClickedCancel] = useState(false)
  const [loading, setLoading] = useState(false)
  const [index, setIndex] = useState(0)
  const [cacheOriginData, setCacheOriginData] = useState({})
  const [data, setData] = useState([])

  const updateList = () => {

    getFamilyInfo(employeeId).then((res = []) => {
      setData(res.map((item, index) => {
        return { ...item, key: index }
      }))
      setLoading(false)
    })
  }

  useEffect(() => {
    updateList()
  }, [])

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0]

  const toggleEditable = (e, key) => {
    e.preventDefault()
    const newData = data?.map((item) => ({ ...item }))
    const target = getRowByKey(key, newData)
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = { ...target }
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable
      setData(newData)
    }
  }

  const newMember = () => {
    const newData = data?.map((item) => ({ ...item })) || []
    newData.push({
      key: `NEW_TEMP_ID_${index}`,
      editable: true,
      isNew: true,
      empoid: employeeId,
    })
    setIndex(index + 1)
    setData(newData)
  }

  const remove = (oid) => {
    setLoading(true)
    deleteFamilyInfo(oid).then(() => {
      updateList()
    })
  }

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data]
    const target = getRowByKey(key, newData)

    if (target) {
      target[fieldName] = e.target ? e.target.value : e
      setData(newData)
    }

  }

  const saveRow = (e, rowKey) => {
    e.persist()
    setLoading(true)
    if (clickedCancel) {
      setClickedCancel(false)
      return
    }
    const target = getRowByKey(rowKey) || {}
    if(checkPhone(parseInt(target.phone))){
      message.error("联系方式格式错误！")
      setLoading(false)
      return
    }
    toggleEditable(e, rowKey)
    const { isNew, editable, key, ...payload } = target

    addFamilyInfo(payload).then(() => {
      updateList()
    })
  }

  const updateRow = (e, rowKey, oid) => {
    e.persist()
    setLoading(true)
    if (clickedCancel) {
      setClickedCancel(false)
      return
    }
    const target = getRowByKey(rowKey) || {}
    if(checkPhone(parseInt(target.phone))){
      message.error("联系方式格式错误！")
      setLoading(false)
      return
    }
    toggleEditable(e, rowKey)
    const { isNew, editable, key, ...payload } = target
    updateFamilyInfo({ oid, ...payload }).then(() => {
      updateList()
    })
  }

  const cancel = (e, key) => {
    setClickedCancel(true)
    e.preventDefault()
    const newData = [...data] // 编辑前的原始数据

    let cacheData = []
    cacheData = newData.map((item) => {
      if (item.key === key) {
        if (cacheOriginData[key]) {
          const originItem = { ...item, ...cacheOriginData[key], editable: false }
          delete cacheOriginData[key]
          setCacheOriginData(cacheOriginData)
          return originItem
        }
      }

      return item
    })
    setData(cacheData)
    setClickedCancel(false)
  }

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input
              value={text}
              autoFocus
              onChange={(e) => handleFieldChange(e, 'name', record.key)}
              placeholder="姓名"
            />
          )
        }
        return text
      },
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'gender', record.key)}>
              {genderList.map((item, index) => {
                return (
                  <Option value={`${item.value}`} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = genderList.find((item) => item.value === text)
        return res ? res.label : text
      },
    },
    {
      title: '与本人关系',
      dataIndex: 'relation',
      key: 'relation',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'relation', record.key)}>
              {relationList.map((item, index) => {
                return (
                  <Option value={`${item.value}`} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = relationList.find((item) => item.value === text)
        return res ? res.label : text
      },
    },
    {
      title: '工作单位',
      dataIndex: 'company',
      key: 'company',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input
              value={text}
              autoFocus
              onChange={(e) => handleFieldChange(e, 'company', record.key)}
              placeholder="工作单位"
            />
          )
        }
        return text
      },
    },
    {
      title: '联系号码',
      dataIndex: 'phone',
      key: 'phone',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input
              value={text}
              autoFocus
              onChange={(e) => handleFieldChange(e, 'phone', record.key)}
              placeholder="联系号码"
            />
          )
        }
        return text
      },
    },
    {
      title: '是否紧急联系人',
      dataIndex: 'isEmergencyContact',
      key: 'isEmergencyContact',
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'isEmergencyContact', record.key)}>
              {yesOrNoList.map((item, index) => {
                return (
                  <Option value={`${item.value}`} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = yesOrNoList.find((item) => item.value === text)
        return res ? res.label : text
      },
    },
    {
      title: '操作',
      key: 'action',
      width: '160px',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }

        if (record.editable) {
          if (record.isNew) {
            return (
              <span>
                <a onClick={(e) => saveRow(e, record.key)}>添加</a>
                <Divider type="vertical"/>
                <Popconfirm title="是否要删除此行？" cancelText='取消' okText='确认' onConfirm={updateList}>
                  <a>删除</a>
                </Popconfirm>
              </span>
            )
          }

          return (
            <span>
              <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
          )
        }

        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否要删除此行？" cancelText='取消' okText='确认' onConfirm={() => remove(record.oid)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      },
    },
  ]
  return (
    <>
      <Table
        loading={loading}
        columns={columns}
        dataSource={data}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
      />
      <Button
        style={{
          width: '100%',
          marginTop: 16,
          marginBottom: 8,
        }}
        type="dashed"
        onClick={newMember}
      >
        <PlusOutlined/>
        新增成员
      </Button>
    </>
  )
}

export default connect(({ recruitment }) => ({
  recruitment,
}))(TableForm)

